#!/bin/bash
{%- set etcdnode=[] %}
{%- if groups['etcd'] is not defined %}
    {%- for host in groups['master'] %}
        {{ etcdnode.append(host) }}
    {%- endfor%}
{%- else%}
    {%- for host in groups['etcd'] %}
        {{ etcdnode.append(host) }}
    {%- endfor%}
{%- endif %}

command -v jq > /dev/null 2>&1 || exit 1
FILENAME=$(date +%Y-%m-%d)
LEADER=$(/usr/local/bin/etcdctl --endpoints {% for host in etcdnode %}{{ host }}:2379{% if not loop.last %},{% endif %}{% endfor %} --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/healthcheck-client.crt --key /etc/kubernetes/pki/etcd/healthcheck-client.key endpoint status --write-out=json | jq .[0].Status.leader)

ENDPOINT=$(/usr/local/bin/etcdctl --endpoints {% for host in etcdnode %}{{ host }}:2379{% if not loop.last %},{% endif %}{% endfor %} --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/healthcheck-client.crt --key /etc/kubernetes/pki/etcd/healthcheck-client.key endpoint status --write-out=json | jq -r ".[] | select(.Status.header.member_id == ${LEADER}) | .Endpoint")

ETCDCTL_API=3 /usr/local/bin/etcdctl \
--command-timeout=3s \
--endpoints ${ENDPOINT} \
--cacert /etc/kubernetes/pki/etcd/ca.crt \
--cert /etc/kubernetes/pki/etcd/server.crt \
--key /etc/kubernetes/pki/etcd/server.key snapshot save {{ etcd.backupDir | default("/tmp") }}/kubernetes-etcd.${FILENAME}.snapshot.db

find {{ etcd.backupDir | default("/tmp") }}/kubernetes-etcd.*.snapshot.db -mtime +30 -exec rm -r {} \;